/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package almacen;

import java.sql.*;
import java.text.ParseException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SpinnerNumberModel;
import resources.local_connection;

/**
 *
 * @author Tesla
 */
public final class Transferir extends javax.swing.JDialog {

    boolean actualizando = false;
    Connection cn;
    PreparedStatement ps;
    ResultSet rs;
    static int code;
    int fromSuc;
    int toSuc;
    float entero1 = 0, entero2 = 0;
    Vector sucursales = new Vector();

    /**
     * Creates new form Transferir
     */
    public Transferir(java.awt.Frame parent, boolean modal, int cd) {
        super(parent, modal);
        initComponents();
        fromSuc = Almacen.suc1;
        toSuc = Almacen.suc2;
        code = cd;
        try {
            cn = local_connection.getconnect();
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
        cargarSucursales();
        cargarCantidades();
        jSpinner1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSpinner1StateChanged(evt);
            }
        });
        jSpinner2.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSpinner2StateChanged(evt);
            }
        });
    }

    private void jSpinner2StateChanged(javax.swing.event.ChangeEvent evt) {
          //if(!(evt.getSource() instanceof JSpinner))
        if (actualizando == false) {
            actualizando = true;
            actualizarCantidades(2);
            actualizando = false;
        }
    }

    private void jSpinner1StateChanged(javax.swing.event.ChangeEvent evt) {
       // System.out.println(evt);
        // if(!(evt.getSource() instanceof JSpinner))
        if (actualizando == false) {
            actualizando = true;
            actualizarCantidades(1);
            actualizando = false;
        }
    }
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        sucursal1 = new javax.swing.JComboBox();
        sucursal2 = new javax.swing.JComboBox();
        jSpinner1 = new javax.swing.JSpinner();
        jSpinner2 = new javax.swing.JSpinner();
        lblCantidad1 = new javax.swing.JLabel();
        lblCantidad2 = new javax.swing.JLabel();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Transferir producto");
        setIconImage(new ImageIcon(getClass().getResource("/resources/logo_rayito.png")).getImage());

        jButton1.setText("Guardar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Salir");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        sucursal1.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                sucursal1PopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });

        sucursal2.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                sucursal2PopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });

        jSpinner1.setModel(new javax.swing.SpinnerNumberModel(Double.valueOf(0.0d), Double.valueOf(0.0d), null, Double.valueOf(1.0d)));

        jSpinner2.setModel(new javax.swing.SpinnerNumberModel(Double.valueOf(0.0d), Double.valueOf(0.0d), null, Double.valueOf(1.0d)));

        lblCantidad1.setText("jLabel2");

        lblCantidad2.setText("jLabel3");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblCantidad1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jSpinner1)
                        .addComponent(sucursal1, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(sucursal2, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 94, Short.MAX_VALUE)
                    .addComponent(jSpinner2)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(lblCantidad2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sucursal1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sucursal2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(5, 5, 5)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCantidad1)
                    .addComponent(lblCantidad2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSpinner2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap(12, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cargarSucursales() {
        try {
            ps = cn.prepareStatement("select nombre, id from sucursales where activo = 1");
            rs = ps.executeQuery();
            while (rs.next()) {
                sucursal1.addItem(rs.getString(1));
                sucursal2.addItem(rs.getString(1));
                sucursales.add(rs.getInt(2));
            }
            sucursal1.setSelectedIndex(sucursales.indexOf(fromSuc));
            sucursal2.setSelectedIndex(sucursales.indexOf(toSuc));
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }

    private void cargarCantidades() {
        try {
            ps = cn.prepareStatement("Select cantidad from stock where sucursal = ? and id_producto = ?");
            ps.setInt(1, fromSuc);
            ps.setInt(2, code);
            rs = ps.executeQuery();
            if (rs.next()) {
                if (rs.getObject(1) != null) {
                    lblCantidad1.setText(rs.getString(1));
                    entero1 = rs.getFloat(1);
                    //System.out.println("si cargo");
                } else {
                    entero1 = 0.0f;
                    lblCantidad1.setText("0");
                }
            } else {
                entero1 = 0.0f;
                lblCantidad1.setText("0");
            }
            ps = cn.prepareStatement("Select cantidad from stock where sucursal = ? and id_producto = ?");
            ps.setInt(1, toSuc);
            ps.setInt(2, code);
            rs = ps.executeQuery();
            if (rs.next()) {
                if (rs.getObject(1) != null) {
                    lblCantidad2.setText(rs.getString(1));
                    entero2 = rs.getFloat(1);
                } else {
                    entero1 = 0.0f;
                    lblCantidad2.setText("0");
                }
            } else {
                lblCantidad2.setText("0");
                entero2 = 0.0f;
            }
            jSpinner1.setModel(new SpinnerNumberModel(0, 0, (entero2>0)?entero2:0, 1));
            jSpinner2.setModel(new SpinnerNumberModel(0, 0, (entero1>0)?entero1:0, 1));
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (sucursal1.getSelectedIndex() == sucursal2.getSelectedIndex()) {
            JOptionPane.showMessageDialog(this, "No se puede transferir de y hacia la misma sucursal", "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            try {
                jSpinner1.commitEdit();
                jSpinner2.commitEdit();
                //  ps=cn.prepareStatement("INSERT INTO stock(id_producto,cantidad,ubicacion,sucursal,minimo) VALUES("+code+","+spinnerCantidad.getValue()+",'',"+toSuc+",0) ON DUPLICATE KEY UPDATE cantidad=cantidad+"+spinnerCantidad.getValue());
                ps = cn.prepareStatement("INSERT INTO transferencias(id_producto,suc1,suc2,despues1,despues2,id_usuario) values(?,?,?,?,?,?)");
                ps.setInt(1, code);
                ps.setInt(2, fromSuc);
                ps.setInt(3, toSuc);
                ps.setDouble(4, Double.parseDouble(lblCantidad1.getText()));
                ps.setDouble(5, Double.parseDouble(lblCantidad2.getText()));
                ps.setInt(6, Almacen.idUsuario);
                ps.execute();

                this.dispose();
                // TODO add your handling code here:
            } catch (SQLException | ParseException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void sucursal1PopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_sucursal1PopupMenuWillBecomeInvisible
        fromSuc=(int) sucursales.get(sucursal1.getSelectedIndex());
        cargarCantidades();
        // TODO add your handling code here:
    }//GEN-LAST:event_sucursal1PopupMenuWillBecomeInvisible

    private void sucursal2PopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_sucursal2PopupMenuWillBecomeInvisible
        toSuc=(int) sucursales.get(sucursal2.getSelectedIndex());
        cargarCantidades();
        // TODO add your handling code here:
    }//GEN-LAST:event_sucursal2PopupMenuWillBecomeInvisible
    private void actualizarCantidades(int n) {
        if (n == 1) {
            jSpinner2.setValue(0.0);
            lblCantidad1.setText(String.valueOf(((double) entero1 + (double) jSpinner1.getValue())));
            lblCantidad2.setText(String.valueOf(((double) entero2 - (double) jSpinner1.getValue())));
        } else {
            jSpinner1.setValue(0.0);
            lblCantidad2.setText(String.valueOf( ((double) entero2 + (double) jSpinner2.getValue())));
            lblCantidad1.setText(String.valueOf( ((double) entero1 - (double) jSpinner2.getValue())));
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JSpinner jSpinner1;
    private javax.swing.JSpinner jSpinner2;
    private javax.swing.JLabel lblCantidad1;
    private javax.swing.JLabel lblCantidad2;
    private javax.swing.JComboBox sucursal1;
    private javax.swing.JComboBox sucursal2;
    // End of variables declaration//GEN-END:variables
}
